package com.coder.algorithm.leetcode

/**
 * [557. 反转字符串中的单词 III](https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/)
 * [151. 颠倒字符串中的单词](https://leetcode-cn.com/problems/reverse-words-in-a-string/)
 *
 * @author yuhus
 * @date: 2022/3/30
 */
object l_0556 {
    fun reverseWords(s: String): String {
        val charArray = s.toCharArray()
        var start = 0
        for (i in charArray.indices) {
            if (i == charArray.size - 1) {
                reverseWords(charArray, start, i)
            } else if (charArray[i] == ' ') {
                reverseWords(charArray, start, i - 1)
                start = i + 1
            }
        }
        return String(charArray)
    }

    private fun reverseWords(charArray: CharArray, l: Int, r: Int) {
        var left = l
        var right = r
        while (left < right) {
            val temp = charArray[left]
            charArray[left] = charArray[right]
            charArray[right] = temp
            left++
            right--
        }
    }
}